package com.joinlabs.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.joinlabs.entity.Comment;
import com.joinlabs.entity.Img;
import com.joinlabs.entity.Log;
import com.joinlabs.entity.Weibo;
import com.joinlabs.service.IFindCommentByidService;
import com.joinlabs.service.IFindweiboDetialByidService;
import com.joinlabs.service.ILogService;
import com.joinlabs.service.IUserService;

@Controller
@RequestMapping("/weiboDetail")
@SessionAttributes(names= {"weiboDetail","firstimg","firstList"})
public class WeibodetailAction {
	  @Resource
	   private IUserService userService;//用户
	  @Resource
		private ILogService logService;// 日志
	  @Resource
	   private IFindCommentByidService findCommentService;//评论内容
	  @Resource 
	  private IFindweiboDetialByidService weiboDetialByidService;//找微博详情
		@RequestMapping("/detail")
		public ModelAndView Detail(String WBid,ModelMap map) {
		   //传入微博id查询微博详情
			Weibo  weiboDetail =weiboDetialByidService.selectDetailMsg(Long.parseLong(WBid));
			//第一张图
			Img firstimg=weiboDetail.getImgList().get(0);
			map.addAttribute("firstimg",firstimg);
			map.addAttribute("weiboDetail",weiboDetail);
			// 查询所有日志
			List<Log> logList = logService.selectAllLog();
			map.addAttribute("logList", logList); 
			//找评论
			 List<Comment> commentlist=findCommentService.selectAllCommentByWBid(Long.parseLong(WBid));

			 List<Comment> firstList = new ArrayList<>();
			 
			 //list长度为3
			 //改造list,让长度为1，还有两个回复在 评论实体里面的 list中
			 for(int i = 0;i<commentlist.size();i++) {
				 
				 Comment comm = commentlist.get(i);
				 
				 if(comm.getCommentedId() == 0) {	 
					 //说明是对微博的评论
					 comm.setCommentlist(new ArrayList<>());
					 firstList.add(comm);
					 
				 }

			 }

			 for(int i = 0;i<commentlist.size();i++) {
				 
				 Comment comm2 = commentlist.get(i);
				 if(comm2.getCommentedId() != 0) {
					 
					 //对评论的评论
					 //到底是对哪个评论的评论
					 for(int j = 0;j<firstList.size();j++) {
						 if(firstList.get(j).getCommentId() == comm2.getCommentedId()) {
							 firstList.get(j).getCommentlist().add(comm2);
							 break;
						 }
					 }
				 }
				 
			 }
			 map.addAttribute("firstList",firstList);
			 map.addAttribute("commentlist",commentlist);
			return new ModelAndView("/detailPage/detail");
		}
		 @RequestMapping("/showTranto")
		 public String select() {
			 
			 return "/detailPage/Detailtranto";
		 }
}
